﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ObjectGraph.Core.Interfaces;

namespace ObjectGraph.Core
{
    public class GenericAction : IAction
    {
        public delegate void Operation();
        Operation m_undoOp;
        Operation m_redoOp;

        public GenericAction(Operation undoOp, Operation redoOp)
        {
            m_undoOp = undoOp;
            m_redoOp = redoOp;
        }

        #region IAction Members

        public virtual void Undo()
        {
            if (m_undoOp != null)
                m_undoOp();
        }

        public virtual void Redo()
        {
            if (m_redoOp != null)
                m_redoOp();
        }

        #endregion
    }

    public class GenericCollectionAction : GenericAction, ICollectionAction
    {
        ECollectionActionType m_actionType;

        public GenericCollectionAction(ECollectionActionType actionType, Operation addOp, Operation removeOp)
            : base(addOp, removeOp)
        {
            m_actionType = actionType;
        }

        public virtual void PerformAdd() { base.Undo(); }
        public virtual void PerformRemove() { base.Redo(); }

        public override void Undo()
        {
            SwitchActionType();
        }

        public override void Redo()
        {
            SwitchActionType();
        }

        public virtual void SwitchActionType()
        {
            if (m_actionType == ECollectionActionType.Add)
            {
                PerformRemove();
                m_actionType = ECollectionActionType.Remove;
            }
            if (m_actionType == ECollectionActionType.Remove)
            {
                PerformAdd();
                m_actionType = ECollectionActionType.Add;
            }
        }

        #region ICollectionAction Members

        public ECollectionActionType ActionType
        {
            get { return m_actionType; }
        }

        #endregion
    }
}
